/**
 * Created by Administrator on 2017/5/5.
 */
const randomString = require('randomstring');
let moment = require('moment');
const _ = require('lodash');
const PromiseA = require('bluebird');
const originData = require('./data');
let cc = 0;  // 客户编号
const constctor = require('./constrctor');
// 创建客户
exports.createCustomers = function (client, id) {
    // 创建客户
    return PromiseA.mapSeries(originData.customers, customer => {
        customer.sellerId = id;
        const data = _.assign({}, customer, {
            name: customer.name + (cc++),
            rebate: Math.floor(Math.random() * 100 % 80)
        });
        return client.customer.create({data}).then((cu) => {
            let yy = 0;
            let pp = 0;
            console.log(cu.id);
            return PromiseA.mapSeries(originData.weibos, weibo => {
                // 为客户创建微博
                return client.customer.createWeibos(cu.id, {
                    data: _.assign({}, weibo, {
                        accountId: id,
                        weiboAccount: cu.name + weibo.weiboAccount + (pp),
                        uid: cu.name + weibo.uid + (pp),
                        nickname: cu.name + weibo.nickname + (pp),
                        password: cu.name + weibo.password + (pp)
                    })
                });
                pp++;
            }).then(() => {
                // 发起一次充值
                return constctor.createCustomerRecharge1(client, id, cu.id).then((recharge) => {
                    console.log(recharge);
                    return constctor.updateCustomerRecharge(client, recharge.id);
                })
            });
        });
    })
};
exports.createCustomerRecharge1 = function (client, userId, customerId) {
    // return client.customer.find({
    //     // filter: {include: 'bankAccounts'},
    //     // where: {id: "B1rRkf92HZ"}
    //     // where: {sellerId: (accounts[random() * 10 % (accounts.length)])}
    // }).then(customers => {
    // return client.customer.findById('B1rRkf92HZ').then(customers => {
    //     customers = [customers];
    // return PromiseA.mapSeries(customers, (customer, index) => {
    //     if (index > 10) return;
    // const amount = Math.floor(Math.random() * 100000 % 100000) || 10000;
    const amount = 1000;
    // const id = accounts[Math.floor(Math.random() * 10) % (accounts.length)];
    const data = _.assign({}, originData.customerRecharge, {
        amount: 1000,
        feeService: 100,
        // bankAccountId: customer.bankAccounts[0] && customer.bankAccounts[0].id,
        sponsorId: userId,
        createdAt: moment().subtract(Math.floor(Math.random() * 10 % 3)+1, 'month').toDate(),
        // rebate: 12
        rebate: Math.floor(Math.random() * 100 % 30)
    });

    return client.customer.createCustomerRecharges(customerId, {data});
    // return;
    // });
    // });
};


exports.createBankAccounts = function (client) {
    let cc = 10;
    return client.customer.find().then(customers => {
        // 获取客户
        return PromiseA.mapSeries(customers, customer => {
            // 为客户创建银行卡
            // originData.bankInfo.bankAccount += Math.floor(Math.random() * 100 % 9);
            const data = _.assign({}, originData.bankInfo, {bankAccount: originData.bankInfo.bankAccount + (cc++)});
            return client.customer.createBankAccounts(customer.id, {data});
        })
    });
};
// 为每位客户创建两个充值 一个充值 一个续费
// 现在创建一个
exports.createCustomerRecharge = function (client, accounts) {
    return client.customer.find({
        // filter: {include: 'bankAccounts'},
        // where: {id: "B1rRkf92HZ"}
        // where: {sellerId: (accounts[random() * 10 % (accounts.length)])}
    }).then(customers => {
        // return client.customer.findById('B1rRkf92HZ').then(customers => {
        //     customers = [customers];
        return PromiseA.mapSeries(customers, (customer, index) => {
            if (index > 10) return;
            // const amount = Math.floor(Math.random() * 100000 % 100000) || 10000;
            const amount = 1000;
            const id = accounts[Math.floor(Math.random() * 10) % (accounts.length)];
            const data = _.assign({}, originData.customerRecharge, {
                amount: amount,
                feeService: 100,
                // bankAccountId: customer.bankAccounts[0] && customer.bankAccounts[0].id,
                sponsorId: id,
                createdAt: moment().subtract(Math.floor(Math.random() * 10 % 3), 'month').toDate(),
                // rebate: 12
                rebate: Math.floor(Math.random() * 100 % 30)
            });
            console.log(id);
            if (customer.id)
                return client.customer.createCustomerRecharges(customer.id, {data});
            return;
        });
    });
};

// 财务确认处理
exports.updateCustomerRecharge = function (client, id) {
    console.log(id, 'id');
    if (id)
        return client.customerRecharge.handle(id, {data: {status: 'handle', remarks: '这是确认说明'}});
};
// 创建部门
exports.createDepartment = function (client, ownerId) {
    return PromiseA.mapSeries(originData.departments, deparment => {
        return client.department.create({
            data: _.assign({}, {
                name: deparment.name,
                departmentsOwnerId: ownerId
            })
        });
    });
};
// 从创建组
exports.createGroup = function (client, ownerId) {
    return client.department.find().then(departments => {
        return PromiseA.mapSeries(departments, department => {
            // 创建组
            return PromiseA.mapSeries(originData.groups, group => {
                const data = _.assign(group, {groupsOwnerId: ownerId});
                return client.department.createGroups(department.id, {data});
            });
        })
    })
};

// 给组创建组员
exports.createMembers = function (client) {
    return client.group.find().then(groups => {
        let mail = 10000;
        return PromiseA.mapSeries(groups, group => {
            // 给每个组创建3名员工
            return PromiseA.mapSeries(originData.members, member => {
                const mobile = '137518' + (mail++); //创建手机号
                console.log(mobile);
                // 1418
                const data = _.assign(member, {
                    mobile: mobile,
                    username: member.nickname + mobile,
                    departmentId: group.departmentId,
                    title: originData.titles[Math.floor(Math.random() * 100 % 5)]
                });
                return client.group.createGroupMembers(group.id, {data});
            })
        });
    });
};
const c = require('./constrctor');
//　为用户创建客户
exports.createCustomerForUser = function (client) {
    return client.account.find({where: {username: {neq: 'admin'}}}).then(users => {
        return PromiseA.mapSeries(users, user => {
            return c.createCustomers(client, user.id);
        });
    })
};
// 为客户创建微博账号
exports.createWeiBo = function (client) {
    return client.customer.find().then(customers => {
        return PromiseA.mapSeries(customers, customer => {
            return c.createWeiboAcccount(client, customer.id);
        });
    })
};

exports.createGroupPlan = function (client, groupId, departmentId) {
    return PromiseA.mapSeries(originData.salesPlans, salesPlan => {
        const data ={
                groupId: groupId,
                new: Math.random() * 10000010 % 10000,
                date: moment().subtract(salesPlan, 'month').toDate(),
                renewal: Math.random() * 10000010 % 10000,
                departmentId: departmentId
            };
        return client.salesPlan.SaleReport({data});
    });
};

// 创建一个用户 并且加入一个组
exports.createUser = function (client) {
    const user = {
        nickname: 'xiaogang',
        mobile: '13751821418',
        email: '715709084@qq.com',
        username: 'xiaogang',
        password: "mmp0ss"
    };
    return PromiseA.all([
        client.group.findOne(),
        client.account.create({data: user}).then(user => {
            return client.account.addRole(user.id, 'admin').then(() => {
                return user;
            });
        }),
        // client.customer.findOne()
    ]).then(([group, operator, customer]) => {
        const groupId = group.id;
        const departmentId = group.departmentId;
        return client.account.patchAttributes(operator.id, {data: {groupMembersId: groupId, departmentId}}).then(() => {
            // const data = _.assign(originData.weibos[0], {accountId: operator.id, customerId: customer.id});
            // // 创建微博账号
            // return client.weibo.create({data});
        });
    });
};

// 創建微博的recharge
exports.creeateWeiboRecharge = function (client, userId) {
    return PromiseA.all([client.customer.findById("B1rRkf92HZ"), client.weibo.findOne({filter: {where: {"customerId": "B1rRkf92HZ"}}})]).then((res) => {
        const [customer, weibo] = res;
        const data = {
            // amount: 63,
            // amount: Math.floor(Math.random() * 10000 % 50),
            amount: 620,
            customerId: weibo.customerId,
            weiboId: weibo.id,
            sponsorId: userId
        };
        return client.weiboRecharge.create({data});
    });
};
exports.creeateWeiboRecharge11 = function (client, userId, weibos) {
    // return PromiseA.all([client.customer.findById("B1rRkf92HZ"), client.weibo.findOne({filter: {where: {"customerId": "B1rRkf92HZ"}}})]).then((res) => {
    //     const [customer, weibo] = res;
    return PromiseA.mapSeries(weibos, weibo => {
        const data = {
            // amount: 63,
            amount: Math.floor(Math.random() * 10000 % 50),
            // amount: 20,
            customerId: weibo.customerId,
            weiboId: weibo.id,
            sponsorId: userId
        };
        return client.weiboRecharge.create({data}).then((rechage) => {
            return client.weiboRecharge.handle(rechage.id, {data: {status: 'handle', remarks: '合适确认说明'}}).then(() => {
                return constctor.createMaterials12(client, userId, weibo.id)
            });
        });
    });
};
exports.creeateWeiboRecharge1 = function (client, userId) {
    return client.weibo.find().then(weibos => {
        return PromiseA.mapSeries(weibos, weibo => {
            return PromiseA.mapSeries(originData.weiboRecharges, weiboRecharge => {
                const data = {
                    amount: Math.floor(Math.random() * 10000 % 1000),
                    customerId: weibo.customerId,
                    weiboId: weibo.id,
                    sponsorId: userId
                };
                return client.weiboRecharge.create({data});
            });
        });
    }).then(res => {
        return _.flattenDeep(res);
    });
};
// 创建一个微博账号
exports.createWeiboAcccount = function (client, userId) {
    return client.customer.findOne().then((customer => {
        const data = _.assign(originData.weibos[0], {accountId: userId, customerId: customer.id});
        // 创建微博账号
        return client.weibo.create({data});
    }));
};
// 创建 meterail
exports.createMaterials = function (client, userid) {
    let aaa = 4;
    return client.weiboBalance.find({filter: {where: {"weiboId": "HJNYYFrIW"}}}).then(weiboBalances => {
        return PromiseA.mapSeries(weiboBalances, weiboBalance => {
            // return client.account.getWeibos(userid).then(([weibos]) => {
            // const data = _.assign(originData.materials[0], {weiboId: weibos[0].id});
            // return client.account.createMaterials(userid, {data});
            // 十天消耗
            return PromiseA.mapSeries(originData.operationDailies, operationDailiy => {
                const t = 2;
                console.log(t);
                // const t = Math.floor(Math.random() * 10000 % 5)+1;
                return client.operationDaily.weiboReport({
                    data: {
                        date: moment().subtract(operationDailiy, 'day'),
                        material: t,
                        planMaterial: t,
                        consumption: t,
                        planConsumption: t,
                        accountId: userid,
                        weiboId: weiboBalance.weiboId
                    }
                })
            });
        });
    });
};
exports.createMaterials12 = function (client, userId, weiboId) {
    let aaa = 4;
    console.log(userId, " 123");
    // return client.weiboBalance.find({filter: {where: {"weiboId": "HJNYYFrIW"}}}).then(weiboBalances => {
    //     return PromiseA.mapSeries(weiboBalances, weiboBalance => {
    // return client.account.getWeibos(userid).then(([weibos]) => {
    // const data = _.assign(originData.materials[0], {weiboId: weibos[0].id});
    // return client.account.createMaterials(userid, {data});
    // 十天消耗
    return PromiseA.mapSeries(originData.operationDailies, operationDailiy => {
        // const t = 2;
        // console.log(t);
        const t = Math.floor(Math.random() * 10000 % 50)+1;
        return client.operationDaily.weiboReport({
            data: {
                date: moment().subtract(operationDailiy, 'day'),
                material: t,
                planMaterial: t,
                consumption: t,
                planConsumption: t,
                accountId: userId,
                weiboId: weiboId
            }
        })
    });
    // });
    // });
};
//
exports.createPlans = function (client) {
    return client.group.find({filter: {where: {departmentId: 'dc097980-9b56-11e6-bea5-6b7423f0508a'}}}).then(groups => {
        return PromiseA.mapSeries(groups, group => {
            return constctor.createGroupPlan(client, group.id, "dc097980-9b56-11e6-bea5-6b7423f0508a");
        });
    });
};
exports.getDepartmentAggregate = function (client) {
    const ss = {
        "aggregate": {
            "$group": {
                "id": "$departmentId",
                "amount_sum": {"$sum": "$amount"},
                "serviceFee_sum": {"$sum": "$feeService"}
            }
        },
        "where": {
            "status": "handle",
            "departmentId": "dc097980-9b56-11e6-bea5-6b7423f0508a",
            "createdAt": {"between": ["2017-06-30T16:00:00.000Z", "2017-07-13T10:01:00.843Z"]}
        }
    };

    const filter = {
        aggregateField: 'departmentId',
        departmentId: "dc097980-9b56-11e6-bea5-6b7423f0508a",
        beginDate: moment().startOf('month').subtract(4, 'month').toDate(),
        DateField: 'createdAt',
        endDate: moment().toDate()
    };
    console.log(filter);
    const params = {
        beginDate: moment().startOf('month').subtract(4, 'month').toDate(),
        endDate: moment().toDate()
    };
    return client.customerRecharge.aggregateDepartmentPerformance(params).then(data => {
        console.log(data);
    })
};
exports.getGroupAggregate = function (client) {
    // const filter = {
    //     "aggregate": {
    //         $group: {
    //             'id': '$groupId',
    //             'amount_sum': {
    //                 '$sum': '$amount'
    //             },
    //             'serviceFee_sum': {
    //                 '$sum': '$feeService'
    //             }
    //         }
    //     }
    // };

    const filter = {
        aggregateField: 'groupId',
        departmentId: "dc097980-9b56-11e6-bea5-6b7423f0508a",
        beginDate: moment().startOf('month').subtract(4, 'year').toDate(),
        DateField: 'createdAt',
        endDate: moment().toDate()
    };

    const params = {
        beginDate: moment().startOf('month').subtract(5, 'month').toDate(),
        endDate: moment().toDate()
    };
    return client.customerRecharge.aggregateGroupPerformance(params).then(data => {
        console.log(data);
    })
};

// const filter: {"where":{"type":"income", "createdAt":{"between":["2017-04-30T16:00:00.000Z","2017-05-26T03:45:27.353Z"]}},
//     "aggregate":{"$group":{"id":"$groupId", "amount_sum":{"$sum":"$amount"}}}, "sort":"amount_sum DESC"}


exports.getSellerAggregate = function (client) {
    // const filter = {
    //     // where:{createdAt:{between:[moment().subtract(2,'day').toDate(),moment().toDate()]}},
    //     // "aggregate": {
    //     //     $group: {
    //     //         'id': '$sponsorId',
    //     //         'amount_sum': {
    //     //             '$sum': '$amount'
    //     //         },
    //     //         'serviceFee_sum': {
    //     //             '$sum': '$feeService'
    //     //         }
    //     //     }
    //     // }
    //     where: {
    //         departmentId: 'dc097980-9b56-11e6-bea5-6b7423f0508a',
    //         type: 'new',
    //         createdAt: {between: [moment().startOf('month').toDate(), moment().toDate()]}
    //     },
    //     aggregate: {
    //         $group: {
    //             id: '$sponsorId',
    //             amount_sum: {
    //                 $sum: '$amount'
    //             },
    //             serviceFee_sum: {
    //                 $sum: '$feeService'
    //             }
    //         }
    //
    //     }
    // };

    const filter = {
        aggregateField: '$sponsorId',
        departmentId: "dc097980-9b56-11e6-bea5-6b7423f0508a",
        beginDate: moment().startOf('month').toDate(),
        DateField: 'createdAt',
        endDate: moment().toDate()
    };
    const params = {
        beginDate: moment().startOf('month').toDate(),
        endDate: moment().toDate()
    };
    console.log(filter);
    return client.customerRecharge.aggregateSellerPerformance(params).then(data => {
        console.log(data);
    })
};